package com.wx.mall.operate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.wx.mall.operate.dto.DisUseDto;
import com.wx.mall.operate.dto.DisUseTwoDto;
import com.wx.mall.operate.entity.DisUse;
import com.wx.mall.operate.entity.Discount;
import com.wx.mall.operate.mapper.DisUseMapper;
import com.wx.mall.operate.service.IDisUseService;
import com.wx.mall.operate.service.IDiscountService;
import com.wx.mall.operate.vo.DisUserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 优惠券用户关联 服务实现类
 * </p>
 *
 * @author j
 * @since 2020-05-13
 */
@Service
public class DisUseServiceImpl extends ServiceImpl<DisUseMapper, DisUse> implements IDisUseService {

    @Resource
    private IDiscountService service;
    @Override
    public void addOne(DisUseDto dto) {

        for (Integer disId:dto.getIds()
             ) {
            DisUse disUse=new DisUse();
            disUse.setDisId(disId);
            disUse.setUseId(dto.getUseId());
            Date endTime=service.getById(disId).getEndTime();
             disUse.setEndTime(endTime);
               disUse.setGetTime(new Date());
               disUse.setState(0);
               this.save(disUse);

        }

    };


    @Override
    public List<DisUse> getList(DisUseTwoDto dto) {
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());

        QueryWrapper<DisUse> wrapper=new QueryWrapper<>();

        if(dto.getState()!=null){
            wrapper.eq("state",dto.getState());
        };

        if(dto.getOrderId()!=null){
            wrapper.eq("order_id",dto.getOrderId());
        };
        switch (dto.getSort()){

            case 0:
                wrapper.orderByAsc("end_time");
                break;
            case 1:
                wrapper.orderByAsc("order_id");
                break;
        };

        wrapper.eq("use_id",dto.getUseId());
        List<DisUse> list=this.list(wrapper);
        return list;
    };

    @Override
    public DisUserVo getByUserId(Long id) {

        DisUse disUse=this.getById(id);
        DisUserVo vo=new DisUserVo();
        vo.setDisUse(disUse);
        Discount discount=service.getById(disUse.getDisId());
        vo.setDiscount(discount);
        return vo;
    }
}
